package com.laomuji.android.mvvm.view

import android.content.Context
import android.util.AttributeSet
import androidx.recyclerview.widget.RecyclerView
import com.laomuji.android.mvvm.R
import androidx.core.content.withStyledAttributes


/**
 * 可以设置最大宽高的RecyclerView.
 * @author laomuji666
 * @since 2024/2/21
 */
class LimitRecyclerView : RecyclerView {
    private var maxHeight = 0
    private var maxWidth = 0

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initAttrs(context, attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initAttrs(context, attrs)
    }

    private fun initAttrs(context: Context, attrs: AttributeSet?) {
        context.withStyledAttributes(attrs, R.styleable.LimitRecyclerView) {
            maxWidth = getDimensionPixelSize(R.styleable.LimitRecyclerView_lrvMaxWidth, -1)
            maxHeight = getDimensionPixelSize(R.styleable.LimitRecyclerView_lrvMaxHeight, -1)
        }
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        super.onMeasure(widthSpec, heightSpec)
        var limitWith = measuredWidth
        if (maxWidth >= 0) {
            if (measuredWidth > maxWidth) {
                limitWith = maxWidth
            }
        }
        var limitHeight = measuredHeight
        if (maxHeight >= 0) {
            if (measuredHeight > maxHeight) {
                limitHeight = maxHeight
            }
        }
        setMeasuredDimension(limitWith, limitHeight)
    }
}

